#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# description: ftrace - test for function event triggers
# flags: instance
#
# Ftrace allows to add triggers to functions, such as enabling or disabling
# tracing, enabling or disabling trace events, or recording a stack trace
# within the ring buffer.
#
# This test is designed to test event triggers
#

# The triggers are set within the set_ftrace_filter file
if [ ! -f set_ftrace_filter ]; then
    echo "set_ftrace_filter not found? Is dynamic ftrace not set?"
    exit_unsupported
fi

do_reset() {
    reset_ftrace_filter
    reset_tracer
    disable_events
    clear_trace
    enable_tracing
}

fail() { # mesg
    do_reset
    echo $1
    exit_fail
}

SLEEP_TIME=".1"

do_reset

echo "Testing function probes with events:"

EVENT="sched:sched_switch"
EVENT_ENABLE="events/sched/sched_switch/enable"

cnt_trace() {
    grep -v '^#' trace | wc -l
}

test_event_enabled() {
    val=$1

    e=`cat $EVENT_ENABLE`
    if [ "$e" != $val ]; then
	fail "Expected $val but found $e"
    fi
}

run_enable_disable() {
    enable=$1			# enable
    Enable=$2			# Enable
    check_disable=$3		# 0
    check_enable_star=$4	# 1*
    check_disable_star=$5	# 0*

    cnt=`cnt_trace`
    if [ $cnt -ne 0 ]; then
	fail "Found junk in trace file"
    fi

    echo "$Enable event all the time"

    echo $check_disable > $EVENT_ENABLE
    sleep $SLEEP_TIME

    test_event_enabled $check_disable

    echo "schedule:${enable}_event:$EVENT" > set_ftrace_filter
    if [ -d ../../instances ]; then # Check instances
	cur=`cat set_ftrace_filter`
	top=`cat ../../set_ftrace_filter`
	if [ "$cur" = "$top" ]; then
	    echo "This kernel is too old to support per instance filter"
	    reset_ftrace_filter
	    exit_unsupported
	fi
    fi

    echo " make sure it works 5 times"

    for i in `seq 5`; do
	sleep $SLEEP_TIME
	echo "  test $i"
	test_event_enabled $check_enable_star

	echo $check_disable > $EVENT_ENABLE
    done
    sleep $SLEEP_TIME
    echo " make sure it's still works"
    test_event_enabled $check_enable_star

    reset_ftrace_filter

    echo " make sure it only works 3 times"

    echo $check_disable > $EVENT_ENABLE
    sleep $SLEEP_TIME

    echo "schedule:${enable}_event:$EVENT:3" > set_ftrace_filter

    for i in `seq 3`; do
	sleep $SLEEP_TIME
	echo "  test $i"
	test_event_enabled $check_enable_star

	echo $check_disable > $EVENT_ENABLE
    done

    sleep $SLEEP_TIME
    echo " make sure it stop working"
    test_event_enabled $check_disable_star

    do_reset
}

run_enable_disable enable Enable 0 "1*" "0*"
run_enable_disable disable Disable 1 "0*" "1*"
